import { NextRequest, NextResponse } from 'next/server';

const PINGCODE_API_URL = process.env.NEXT_PUBLIC_PINGCODE_API_URL || 'https://yfxmgl.hainayun.net/open';
const PINGCODE_ACCESS_TOKEN = process.env.NEXT_PUBLIC_PINGCODE_ACCESS_TOKEN || 'a48ae3d4-9b30-4523-9926-899507a77f55';

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const path = searchParams.get('path');
  
  if (!path) {
    return NextResponse.json({ error: 'Path parameter is required' }, { status: 400 });
  }

  try {
    const url = `${PINGCODE_API_URL}${path}`;
    console.log('代理请求:', url);
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${PINGCODE_ACCESS_TOKEN}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('PingCode API 错误:', response.status, response.statusText, errorText);
      return NextResponse.json(
        { error: `PingCode API 错误: ${response.status} ${response.statusText}`, details: errorText },
        { status: response.status }
      );
    }

    const data = await response.json();
    console.log('API 响应成功:', {
      total: data.total,
      page_index: data.page_index,
      page_size: data.page_size,
      values_count: data.values ? data.values.length : 0
    });
    
    return NextResponse.json(data);
  } catch (error) {
    console.error('代理请求失败:', error);
    return NextResponse.json(
      { error: '代理请求失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const path = searchParams.get('path');
  
  if (!path) {
    return NextResponse.json({ error: 'Path parameter is required' }, { status: 400 });
  }

  try {
    const body = await request.json();
    const url = `${PINGCODE_API_URL}${path}`;
    console.log('代理POST请求:', url, body);
    
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${PINGCODE_ACCESS_TOKEN}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('PingCode API 错误:', response.status, response.statusText, errorText);
      return NextResponse.json(
        { error: `PingCode API 错误: ${response.status} ${response.statusText}`, details: errorText },
        { status: response.status }
      );
    }

    const data = await response.json();
    console.log('API POST响应成功:', data);
    
    return NextResponse.json(data);
  } catch (error) {
    console.error('代理POST请求失败:', error);
    return NextResponse.json(
      { error: '代理POST请求失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

export async function PATCH(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const path = searchParams.get('path');
  
  if (!path) {
    return NextResponse.json({ error: 'Path parameter is required' }, { status: 400 });
  }

  try {
    const body = await request.json();
    const url = `${PINGCODE_API_URL}${path}`;
    console.log('代理PATCH请求:', url, body);
    
    const response = await fetch(url, {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${PINGCODE_ACCESS_TOKEN}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('PingCode API 错误:', response.status, response.statusText, errorText);
      return NextResponse.json(
        { error: `PingCode API 错误: ${response.status} ${response.statusText}`, details: errorText },
        { status: response.status }
      );
    }

    const data = await response.json();
    console.log('API PATCH响应成功:', data);
    
    return NextResponse.json(data);
  } catch (error) {
    console.error('代理PATCH请求失败:', error);
    return NextResponse.json(
      { error: '代理PATCH请求失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const path = searchParams.get('path');
  
  if (!path) {
    return NextResponse.json({ error: 'Path parameter is required' }, { status: 400 });
  }

  try {
    const url = `${PINGCODE_API_URL}${path}`;
    console.log('代理DELETE请求:', url);
    
    const response = await fetch(url, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${PINGCODE_ACCESS_TOKEN}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('PingCode API 错误:', response.status, response.statusText, errorText);
      return NextResponse.json(
        { error: `PingCode API 错误: ${response.status} ${response.statusText}`, details: errorText },
        { status: response.status }
      );
    }

    const data = await response.json();
    console.log('API DELETE响应成功:', data);
    
    return NextResponse.json(data);
  } catch (error) {
    console.error('代理DELETE请求失败:', error);
    return NextResponse.json(
      { error: '代理DELETE请求失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}